package com.then.architecture;

import android.app.Application;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;

/**
 * Created by 42524 on 2018/1/24.
 */

public class Country {


    private Application application;

    @Inject
    public Country(Application application) {
        this.application = application;
        init();
    }

    String code;

    String phonePrefix;

    String fullName;

    private Map<String, Country> countries;

    private Country(String code, String phonePrefix, String fullName) {
        this.code = code;
        this.phonePrefix = phonePrefix;
        this.fullName = fullName;
    }


    private void init() {

        String[] countryCode = application.getResources().getStringArray(R.array.common_country_code);
        String[] countryName = application.getResources().getStringArray(R.array.common_country_name);
        String[] countryPhone = application.getResources().getStringArray(R.array.common_country_area_code);

        countries = new HashMap<>(countryCode.length);
        for (int i = 0; i < countryCode.length; ++i) {
            countries.put(countryName[i], new Country(countryCode[i], countryPhone[i], countryName[i]));
        }

    }

    public Map<String, Country> getCountries() {
        return countries;
    }


    public String getCode() {
        return code;
    }

    public Country getDefaultCountryInfo() {
        Country defaultCountry = countries.values().iterator().next();
        TelephonyManager tm = (TelephonyManager) application.getSystemService(Context.TELEPHONY_SERVICE);
        String curPhoneCountryCode = tm.getNetworkCountryIso();

        // 如果没有电话卡，则使用系统语言
        if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE || TextUtils.isEmpty(curPhoneCountryCode)) {
            curPhoneCountryCode = Locale.getDefault().getCountry();
        }
        for (Country country : countries.values()) {
            if (country.code.equalsIgnoreCase(curPhoneCountryCode)) {
                defaultCountry = country;
                break;
            }
        }
        return defaultCountry;
    }


}
